/*************************************************************************
 * @file svrtest.cpp
 * @auth wuwei
 * @created_time Thu 08 Nov 2018 07:45:33 PM CST
 * @brief test program build cmd: "g++ -std=c++11 svrtest.cpp -L. httplib.a -lpthread -o server"
 ************************************************************************/


#include "httplib.h"
#include <string.h>
#include <iostream>
#include <thread>
#include <list>
using namespace std;

list<int> g_oEvent;

//typedef int (*pfRequest) (int anHandle, char* info);

int g_nRecv = 0;

int EventCall (int anHandle, char* info) {

    //cout << "handle:" << anHandle << " info:" << info << endl;
    ++ g_nRecv;
    //SetResponseData(anHandle, 200, 0, "ssssssssssssddfffffff");
    g_oEvent.push_back(anHandle);
    //cout << "SetResult push in list" <<  endl;

    return 0;
}

int GroupCall(char* info) {
    cout << "group call info:" << info << endl; 
    return 0;
}

void dumpThread(int an) {

    int nLast = 0;
    while(true) {
        if (g_nRecv > nLast) {
            cout << " recv :" << g_nRecv << " total; " << g_nRecv - nLast << " per soncd" << endl;
            nLast = g_nRecv;
        }
        std::chrono::milliseconds dura(1000);
        std::this_thread::sleep_for(dura);
    }
}

void ResponseThread(int an) {

    std::chrono::milliseconds dura(50);

    while(true) {
        if (g_oEvent.size() > 0) {
            int nHandle = g_oEvent.front();
            //cout << "ahandle to deal:" << nHandle << endl;
            string result = "handle response:" + to_string(nHandle);
            SetResponseData(nHandle, 200, 1, const_cast<char*>(result.c_str()));
            g_oEvent.pop_front();
        } else {
            std::this_thread::sleep_for(dura);
        }
    }
}


int main() {

  auto worker = std::thread(ResponseThread, 1000);
  auto dumper = std::thread(dumpThread, 1000);

  CreateHttpServer("120.132.38.79:8080");
  SetRouter("Post", "/eee", (void*)EventCall);


  AddGroup("/iii", (void*) GroupCall);
  //GroupAddRouter("get", "/iii", "/bbb", (void*) EventCall);
  //AddGroup("/ggg", (void*) GroupCall);
  SetRouter("get", "/iii/bbb", (void*)EventCall);
  HttpServerRun();
}

